package com.cn.shchuangge.uitls;

import java.io.File;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {

	private static Response mResponse;


	//get请求
	public static Response httpGet(String url) throws IOException{
		 // 01. 定义okhttp
	    OkHttpClient okHttpClient_get = new OkHttpClient();
	    // 02.请求体
	    Request request = new Request.Builder()
	        .get()//get请求方式
	        .url(url)//网址
	        .build();
	        
	    // 03.执行okhttp
	    
	    Response response = okHttpClient_get.newCall(request).execute();
	    return response;
	}
	//post请求
	public static Response httpPost(String name,String passworld,String url) throws IOException {
		// 定义okhttp
		OkHttpClient okHttpClient_post_kv = new OkHttpClient();

		// 定义请求体
		// 执行okhttp
		RequestBody body = new FormBody.Builder()
				.add("name", name)//添加参数体
				.add("passworld", passworld)
				.build();
		Request request = new Request.Builder()
				.post(body) //请求参数
				.url(url)
				.build();
		Response response = okHttpClient_post_kv.newCall(request).execute();

		return response;

	}
	//json请求post
	public static Response jsonPost(String json,String uri) throws IOException {

		OkHttpClient okHttpClient_post_json = new OkHttpClient();
//		String json = "{\n" + "    \"age\": \"18\",\n" + "    \"name\": \"sy\"\n" + "}";
		RequestBody body =
				RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
		Request request = new Request.Builder()
				.post(body)
				.url(uri)
				.build();
		Response response = okHttpClient_post_json.newCall(request).execute();
		return response;

	}
	//上传图片等资源文件post请求
	public static Response imagePost(File file,String uri) throws IOException {
		OkHttpClient okHttpClient_upload = new OkHttpClient();

		//File file = new File(Environment.getExternalStorageDirectory() + "/download", "file.txt");
		RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), file);
		Request request = new Request.Builder()
				.post(body)
				.url(uri)
				.build();
		Response response = okHttpClient_upload.newCall(request).execute();
		return response;
	}
	//下载图片等资源
	public static Response getImage(String uri){


		OkHttpClient okHttpClient_down = new OkHttpClient();
		Request request =
				new Request.Builder()
						.get()
						.url(uri)
						.build();
		try {
			mResponse = okHttpClient_down.newCall(request).execute();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return mResponse;
	}
}
